import {PickerOptionData} from "@taroify/core/picker/picker.shared";
import {useState} from "react";
import {Field, Input, Picker, Popup} from "@taroify/core";

export default function PickerField(
    { key, label, options, onChange, value, disabled }:
    { key: string; label: string, options:PickerOptionData[], onChange: (item: any) => void, value: string, disabled?: boolean }) {
    const [open, setOpen] = useState(false);
    const optionMap = options.reduce((sum, cur: {value: string, label: string}) => {
        return {
            ...sum,
            [cur.value] : cur.label
        }
    }, {});
    const handleOpen = () => {
        !disabled && setOpen(true);
    }
    return (
        <>
            <Field label={label} name={key} clickable={!disabled} style={{opacity: disabled ? 0.5 : 1}}>
                <Input
                    readonly
                    disabled={disabled}
                    placeholder={`点击选择${label}`}
                    value={optionMap[value]}
                    onClick={handleOpen}
                />
            </Field>
            <Popup open={open} rounded placement="bottom" onClose={() => setOpen(false)}>
                <Picker
                    title={label}
                    columns={options}
                    onCancel={() => setOpen(false)}
                    onConfirm={(newValue) => {
                        onChange(options.find(c => c.value === newValue[0]))
                        setOpen(false);
                    }}
                />
            </Popup>
        </>
    );
}